package com.balabala.gym_user.service.impl;

import com.balabala.gym_user.constant.SmsConstant;
import com.balabala.gym_user.service.SmsService;
import com.balabala.gym_user.utils.SendSms;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author 何涛
 * @Date: 2023/04/30/ 13:38
 * @description 短信service实现类
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void sendSmsCode(String phone) {
        String code=getSixRandomCode();
        log.info("生成验证码code：{}",code);
        SendSms.sendSms(phone,code);
        BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(SmsConstant.PREFIX_SMS_PHONE + phone);
        boundValueOperations.set(code);
        //设置失效时间
        boundValueOperations.expire(SmsConstant.PHONE_CODE_EXPIRE, TimeUnit.SECONDS);
        log.info("电话：{}的验证码已保存到redis中。。。",phone);

    }

    private String getSixRandomCode() {
        StringBuilder sb=new StringBuilder();
        Random random=new Random();
        int i=SmsConstant.CODE_LENGTH;
        while (i-->0)
        {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

}
